package com.raos.code.controller;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * EasyCaptcha 控制器
 *  官方地址镜像：https://gitee.com/dp9212/EasyCaptcha，
 *  原始地址：https://github.com/whvcse/EasyCaptcha
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/3/23 21:38
 */
@Controller
public class EasyCaptchaController {

    @Autowired
    private Captcha captcha;

    @GetMapping("/")
    public String index() {
        return "login";
    }

    @GetMapping("/login2")
    public String index2() {
        return "login2";
    }

    // 自定义使用
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 长，宽，位数
        Captcha captcha = new SpecCaptcha(100, 42, 5);
        // 设置类型
        captcha.setCharType(Captcha.TYPE_NUM_AND_UPPER); // 数字大写字母
        // 生成验证码
        String code = captcha.text();
        // 输出验证码
        System.out.println("验证码内容 captcha ===> " + code);
        // 验证码放入Session中
        request.getSession().setAttribute("captcha", code);
        // 输出图片
        captcha.out(response.getOutputStream());
    }

    // 配置使用
    @GetMapping("/captcha2")
    public void captcha2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成验证码
        String code = captcha.text();
        // 输出验证码
        System.out.println("验证码内容 captcha ===> " + code);
        // 验证码放入Session中
        request.getSession().setAttribute("captcha", code);
        // 输出图片
        captcha.out(response.getOutputStream());
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(HttpServletRequest request, String code) {
        Object kaptcha = request.getSession().getAttribute("captcha");
        if (!StringUtils.isEmpty(kaptcha) && kaptcha.toString().equalsIgnoreCase(code)) {
            return "验证成功！";
        }
        return "验证失败！";
    }

}
